package com.spark.lola.controller.logistics;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spark.lola.logistics.entity.ExpensesCategory;
import com.spark.lola.logistics.service.ExpensesCategoryService;
import com.spark.lola.logistics.vo.ExpensesDetailVo;
import com.spark.lola.support.common.constant.CommonConstant;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.configuration.OssProperties;
import com.spark.lola.support.mvc.service.ExcelServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: Zhi-peng wang
 * @date: 2020/06/16 13:49
 **/
@Component
public class MyExcelServiceImpl extends ExcelServiceImpl {

    private static Logger logger = LoggerFactory.getLogger(MyExcelServiceImpl.class);

    @Autowired
    private OssProperties ossProperties;

    @Autowired
    private ExpensesCategoryService expensesCategoryService;

    public MyExcelServiceImpl(OssProperties ossProperties) {
        super(ossProperties);
    }

    public <T> ResponseBean create(List<String> heads, List<T> data, Class<?> cls) {
        SimpleDateFormat simpleDay = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String url = "";
        try {
            String relativePath = "/excel/tmp/";
            String path = this.ossProperties.getUploadPath() + relativePath;
            File files = new File(path);
            if (!files.exists()) {
                files.mkdirs();
            }
            String fileName = System.currentTimeMillis() + ".xlsx";
            // 处理头
            List<List<String>> headList = heads.stream().map(Arrays::asList).collect(Collectors.toList());
            headList.addAll(head());
            // 处理数据
            List<List<String>> lists = new ArrayList<>();
            data.forEach(item -> {
                Field[] fields = item.getClass().getDeclaredFields();
                List<String> stringList = new ArrayList<>();
                for (Field field : fields) {
                    //将属性的首字符大写，方便构造get，set方法
                    String name = field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
                    if (name.equalsIgnoreCase("id") || name.equalsIgnoreCase("orderId") ||
                            name.equalsIgnoreCase("preMileage") || name.equalsIgnoreCase("nowMileage") ||
                            name.equalsIgnoreCase("fuelPrice")) {
                        continue;
                    }
                    if (!name.equalsIgnoreCase("expensesDetailVoList")) {
                        try {
                            Method m = item.getClass().getMethod("get" + name);
                            Object o = m.invoke(item);
                            String value = "";
                            if (o != null) {
                                if (o instanceof Date) {
                                    if (name.equalsIgnoreCase("borrowingTime")){
                                        value = simpleDay.format(o);
                                    } else {
                                        value = simpleTime.format(o);
                                    }
                                } else {
                                    value = o.toString();
                                }
                            }
                            stringList.add(value);
                        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            Method m = item.getClass().getMethod("get" + name);
                            List<ExpensesDetailVo> value = (List<ExpensesDetailVo>) m.invoke(item);
                            value.forEach(expensesDetailVo -> {
                                stringList.add(expensesDetailVo.getPrice().toString());
                            });
                        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }
                lists.add(stringList);
            });
            EasyExcel.write(path + fileName, cls).head(headList).sheet("物流分析").doWrite(lists);
            url = this.ossProperties.getDomain() + path + fileName;
        } catch (Exception var10) {
            logger.error("生成失败,{}", var10.getMessage(), var10);
            return ResponseBean.error(var10.getMessage());
        }
        return ResponseBean.success(url);
    }

    private List<List<String>> head() {
        List<List<String>> list = new ArrayList<>();
        // 生成动态头
        // 查询所有分类
        QueryWrapper<ExpensesCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("used", CommonConstant.Y);
        wrapper.orderByAsc("sort");
        List<ExpensesCategory> expensesCategoryList = expensesCategoryService.list(wrapper);
        expensesCategoryList.forEach(expensesCategory -> {
            List<String> stringList = new ArrayList<>();
            stringList.add(expensesCategory.getName());
            list.add(stringList);
        });
        list.add(Collections.singletonList("合计"));
        return list;
    }

}
